/*
 * Copyright (c) ycq_work@163.com
 */

package com.mxg.blog.controller.articleAdmin;

import com.mxg.blog.common.CqLogger;
import com.mxg.blog.common.DetermineLogin;
import com.mxg.blog.common.ResultCode;
import com.mxg.blog.entity.Article;
import com.mxg.blog.entity.User;
import com.mxg.blog.service.ArticleService;
import com.mxg.blog.service.UserService;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author: ycq_work@163.com
 * @DATE: 2023/5/23 22:21
 * 实际删除文章
 */
@Controller
public class PhysicallyDelete {
    CqLogger logger = CqLogger.getInstance();

    private final ArticleService articleService;
    private final UserService userService;

    public PhysicallyDelete(ArticleService articleService,
                            UserService userService)
    {
        this.articleService = articleService;
        this.userService = userService;
    }
    @PostMapping("api/physicallyDelete")
    public ResponseEntity<Map<String, Object>> physicallyDelete(@RequestBody Map<String, String> requestMap) {
        Map<String, Object> resultMap = new HashMap<>();

        DetermineLogin determineLogin = DetermineLogin.getInstance(requestMap.get("userAccount"), userService);
        User user;
        if(determineLogin.startJudge().equals(DetermineLogin.NOT_LOGIN)){
            resultMap.put(ResultCode.code, ResultCode.WRONG_MESSAGE_NOT_LOGIN);
            resultMap.put(ResultCode.message, ResultCode.WRONG_MESSAGE_NOT_LOGIN);
            return ResponseEntity.ok(resultMap);
        }else{
            user = userService.selectUserById(determineLogin.startJudge());
        }

        Integer articleId;
        try{
            articleId = new Integer(requestMap.get("articleId"));
        }catch (Exception e)
        {
            resultMap.put(ResultCode.code, ResultCode.WRONG_CODE_WRONG_EDIT_ARTICLE);
            resultMap.put(ResultCode.message, ResultCode.WRONG_MESSAGE_WRONG_EDIT_ARTICLE);
            return ResponseEntity.ok(resultMap);
        }

        if (user == null) {
            resultMap.put(ResultCode.code, ResultCode.WRONG_CODE_WRONG_USER_ACCOUNT);
            resultMap.put(ResultCode.message, ResultCode.WRONG_MESSAGE_WRONG_USER_ACCOUNT);
        } else {
            resultMap.put(ResultCode.code, ResultCode.SUCCESS_CODE);
            Article article = articleService.getArticleByArticleId(articleId);
            if(article != null)
            {
                articleService.deleteParamsByIds(articleId);
            }
            resultMap.put(ResultCode.message, ResultCode.SUCCESS_MESSAGE);
            logger.print("删除成功, 文章账号" + articleId);
        }

        return ResponseEntity.ok(resultMap);
    }

}
